package com.paw.hand.gateway.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author lvzihai
 * @date 2021/6/16
 **/
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

  public static final String TOKEN_NAME = "token";

  @Override
  public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    log.info("TokenInterceptor requestUrl "+request.getRequestURI());
    String token = request.getHeader(TOKEN_NAME);
    if(StrUtil.isEmpty(token)){
      token = request.getParameter(TOKEN_NAME);
    }
    // 校验token jwt 或者 redis 数据库 此处省略
    if(StrUtil.isNotEmpty(token)){
      return true;
    }

    try {
      response.setStatus(HttpStatus.UNAUTHORIZED.value());
      response.setContentType("application/json;charset=UTF-8");
      PrintWriter out = response.getWriter();
      out.print(HttpStatus.UNAUTHORIZED.getReasonPhrase());
      out.flush();
      out.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return false;
  }
}
